<?php
namespace Kuoqi\Html;
//能阅读的API文档的一个对象
class ReadApiHtml{

    public $focusCls = null;//操作对象
    public $focusMethod = null;//操作对象方法
    public $apitype;//kuoqiDocument
    public $apiname;//接口名称
    public $apigroup;//接口分组
    public $apititle;//接口标题说明，放置到标题部分的说明文档
    public $apihref;//接口的请求地址信息
    public $apimethod;//接口的请求方式
    public $apidata;//接口的请求数据内容
    public $apiok;//接口成功返回的内容信息
    public $apierror;//接口失败返回的内容信息
    public $apiremark;//备注信息，让用户知道的本接口的相关的技术细节
    public $apidate;

    //初始化方法，序列化操作对象的那个方法
    public function __construct($cls,$method = ''){
        $this->focusCls = new \ReflectionClass($cls);
        $this->focusMethod = $method?$method:(\Kuoqi\Index::$app->actioNs);
    }

    //来源于注释的部分
    public function fromNotes(){
        //怎么说呢，直接获取对应方法的注释来创建生成文档，这么理解可能会好点
        $method = $this->focusCls->getMethod($this->focusMethod);

        //$this->apihref = url($method->class.'/'.$method->name);
        $remark = $method->getDocComment();
        if(!preg_match('/\/\*\*([\s\S]+\*)\//',$remark,$lis)){
            return false;
        }
        $remark = trim($lis[1]);
        $rs = preg_match_all("/([\s\S]+?(\n\s*\*))/",$remark,$list);
        if(!$rs){
            return;
        }

        foreach($list[1] as $k=>$v){
            $this->explodeNotesItem(substr($v,0,-strlen($list[2][$k])));
        }

    }


    final function explodeNotesItem($docpart){
        $docpart = trim($docpart);
        //查找第一个：
        $v = substr(strstr($docpart,':'),1);
        $n = substr($docpart,0,-strlen($v) - 1);
        if(strpos($n,'*')===0){
            $n = substr($n,1);
        }
        if($n){
            $this->$n = $v;
        }
    }

    //冲刷当前对象出来
    public function flush(){
        $editor = new \Kuoqi\Html\Editor();
        $api = $editor->addApi(array(
            'type'=>$this->apitype,
            'title'=>$this->apititle,
            'name'=>$this->apiname,
            'group'=>$this->apigroup,
            'href'=>$this->apihref,
            'method'=>$this->apimethod,
            'data'=>$this->apidata,
            'ok'=>$this->apiok,
            'error'=>$this->apierror,
            'remark'=>$this->apiremark,
            'date'=>$this->apidate,
        ));
        $editor->addRow($api);
        return $editor->flush();
    }
}